import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateDepartmentDto } from './dto/create-department.dto';
import { UpdateDepartmentDto } from './dto/update-department.dto';
import { Department } from './entities/department.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
@Injectable()
export class DepartmentService {
  constructor(
      @InjectRepository(Department)
      private readonly departmentRepository: Repository<Department>
      //@Inject(CACHE_MANAGER) private readonly cacheManager: Cache
    ) {}
  async isUserExists(obj){
    const result = await this.departmentRepository.findOne({ 
      where: obj,
    });
    return !!result
  }
  async create(createDepartmentDto: CreateDepartmentDto) {
    try{
        // const isExists = await this.isUserExists({name: createDepartmentDto.name})
        // if(isExists && !createDepartmentDto.id){
        //   throw new HttpException('角色名称不可重复', HttpStatus.INTERNAL_SERVER_ERROR);
        // }
        return await this.departmentRepository.save({
          ...createDepartmentDto
        })
      } catch (error) {
        throw new HttpException(error.message, error.status, {
          cause: error
        });
      }
  }

  async findAll() {
    try {
      return await this.departmentRepository.find({
        select: ['id', 'name', 'status', 'parentId'],
      });
    } catch (error) {
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  async delete(id){
    try {
      return await this.departmentRepository.delete(id);
    } catch (error) {
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
}
